<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24">
                <h4 class="office-label">机构列表</h4>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <!--机构树状图-->
            <el-col :span="4" :xs="24" style="border-right: 0.5px solid #e2e2e2">
                <div class="head-container">
                    <el-input v-model="officeName" placeholder="请输入机构名称" clearable prefix-icon="Search"
                        style="margin-bottom: 20px" />
                </div>
                <div class="head-container">
                    <el-tree :data="officeTree" :props="{ label: 'label', children: 'children' }"
                        :expand-on-click-node="false" :filter-node-method="filterNode" ref="officeTreeRef" node-key="id"
                        highlight-current @node-click="handleNodeClick" />
                </div>
            </el-col>
            <!-- 机构列表 -->
            <el-col :span="20" :xs="24">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="Sort" @click="handleExpand">展开/折叠
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button plain icon="Refresh" @click="binOfficeTreeList">刷新
                        </el-button>
                    </el-col>
                </el-row>
                <!-- 表格 -->
                <el-table ref="officeTable" :data="officeTreeList" style="width: 100%; margin-bottom: 20px" row-key="id"
                    :row-style="setParentBackground" @row-dblclick="dbClickRow" :expand-row-keys="expands"
                    @expand-change="dbClickRow" v-loading="loading">
                    <el-table-column prop="name" label="机构名称" sortable />
                    <el-table-column prop="area" label="所在地区" sortable />
                    <el-table-column prop="sort" label="排序" sortable />
                    <el-table-column prop="code" label="机构编码" sortable />
                    <el-table-column prop="type" label="机构类型" width="100">
                        <template #default="scope">
                            <dict-tag :options="sys_office_type" :value="scope.row.type" />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template #default="scope">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
                            <el-button v-if="!scope.row.children" link type="primary" icon="Delete"
                                @click="handleDelete(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    
        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" @close="reset" @open="openDialog" width="600px" append-to-body>
            <el-form ref="officeRef" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12" v-if="form.parent_id !== 0">
                        <el-form-item label="上级机构" prop="parent_id">
                            <el-tree-select v-model="form.parent_id" :data="officeTree"
                                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                placeholder="选择上级机构" check-strictly :filter-node-method="filterNode" clearable filterable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="归属区域" prop="area_id">
                            <el-tree-select placeholder="选择归属区域" v-model="form.area_id" :data="areaTree"
                                :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                                check-strictly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构名称" prop="name">
                            <el-input v-model="form.name" clearable placeholder="请输入机构名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构编码" prop="code">
                            <el-input v-model="form.code" clearable placeholder="请输入机构编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构类型" prop="type">
                            <el-select @change="handleSelect" v-model="form.type" placeholder="请选择机构类型">
                                <el-option v-for="item in sys_office_type" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构级别" prop="grade">
                            <el-select v-model="form.grade" placeholder="请选择机构等级">
                                <el-option v-for="item in sys_office_grade" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sort">
                            <el-input type="number" v-model="form.sort" placeholder="请输入排序" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="是否启用" prop="useable">
                            <el-select v-model="form.useable" placeholder="请选择是否启用">
                                <el-option v-for="item in yes_no" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="主负责人" prop="primary_person">
                            <el-input v-model="form.primary_person" clearable placeholder="请输入主负责人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="副负责人" prop="deputy_person">
                            <el-input v-model="form.deputy_person" clearable placeholder="请输入副负责人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系地址" prop="address">
                            <el-input v-model="form.address" clearable placeholder="请输入联系地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮政编码" prop="zip_code">
                            <el-input v-model="form.zip_code" clearable placeholder="请输入邮政编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人" prop="master">
                            <el-input v-model="form.master" clearable placeholder="请输入负责人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电话" prop="phone">
                            <el-input v-model="form.phone" clearable placeholder="请输入电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="传真" prop="fax">
                            <el-input v-model="form.fax" clearable placeholder="请输入传真" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" clearable placeholder="请输入邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Office">
	import { getOfficeTree, getOfficeTreeList, filterOfficeTreeList, getOfficeById, getAreaTree, addOffice, updateOffice, delOffice } from '@/api/system/office';

	const { proxy } = getCurrentInstance();
	/* 机构类型数据 机构等级数据 是否启用 */
	const { sys_office_type, sys_office_grade, yes_no } = proxy.useDict("sys_office_type", "sys_office_grade", "yes_no");
	/* 需要展开的行 */
	const expands = ref([]);
	/* 树状图数据过滤词 */
	const officeName = ref('');
	/* 对话框标题 */
	const title = ref('');
	/* 对话框显隐 */
	const open = ref(false);
	/* 表格数据 */
	const officeTreeList = ref([]);
	/* 树状图数据 */
	const officeTree = ref([]);
	/* 地区树状图 */
	const areaTree = ref([]);
	/* 表格加载动画 */
	const loading = ref(true);

	/* 表单数据 */
	const data = reactive({
		form: {},
		rules: {
			parent_id: [{ required: true, message: "上级机构不能为空", trigger: "change" }],
			area_id: [{ required: true, message: "所属区域不能为空", trigger: "change" }],
			name: [{ required: true, message: "机构名称不能为空", trigger: "change" }],
			type: [{ required: true, message: "机构类型不能为空", trigger: "change" }],
			grade: [{ required: true, message: "机构等级不能为空", trigger: "change" }],
			sort: [{ required: true, message: "排序不能为空", trigger: "change" }]
		}
	})

	const { form, rules } = toRefs(data);

	/* 监听过滤词 */
	watch(officeName, val => {
		proxy.$refs["officeTreeRef"].filter(val);
	});
	/** 通过条件过滤节点  */
	const filterNode = (value, data) => {
		if (!value) return true;
		return data.label.indexOf(value) !== -1;
	};

	/** 选择更改 */
	function handleSelect(value) {
		if (value == "1") {
			rules.value.parent_id = [{ required: false, message: "上级机构不能为空", trigger: "blur" }];
		} else {
			rules.value.parent_id = [{ required: true, message: "上级机构不能为空", trigger: "blur" }];
		}
	}

	/** 设置父级机构背景颜色 */
	function setParentBackground(data) {
		if (data.row.parent_id == '0') {
			return { 'background-color': 'rgba(241,241,241,0.21)' }
		}
	}

	/** 双击行处理 */
	function dbClickRow(row, column, event) {
		if (expands.value.includes(row.id + '')) {
			expands.value = expands.value.filter(val => {
				return val != row.id;
			})
		} else {
			expands.value.push(row.id + '');
		}
	}

	/** 处理展开全部或收起全部 */
	async function handleExpand() {
		let arr = proxy.$refs["officeTable"].data;
		if (expands.value.length < 1) {
			expands.value = [];
			arr.map((item, index, arr) => {
				expands.value.push(item.id.toString());
			})
		} else {
			expands.value = [];
		}
	}

	/** 处理树状图节点点击 */
	function handleNodeClick(data, node) {
		// 最顶级节点
		let parent = node;
		while (parent.level > 1) {
			parent = parent.parent;
		}
		filterOfficeTreeList(parent.data.id).then(response => {
			expands.value = [];
			officeTreeList.value = response.data;
			setTimeout(() => {
				handleExpand();
			}, 100);
		})
	}

	/** 处理修改操作 */
	function handleUpdate(row) {
		reset();
		getOfficeById(row.id).then(response => {
			form.value = response.data[0];
			title.value = "修改机构";
			open.value = true;
		});
	}

	/** 处理添加操作 */
	function handleAdd(row) {
		reset();
		if (row.id != undefined) {
			form.value.parent_id = row.id;
		}
		title.value = "添加机构";
		open.value = true;
	}

	/** 处理删除操作 */
	function handleDelete(row) {
		proxy.$modal.confirm('确定要删除“' + row.name + '”部门?').then(() => {
			return delOffice(row.id);
		}).then(response => {
			if (response.code == 200) {
				proxy.$modal.msgSuccess(response.msg)
			} else {
				proxy.$modal.msgError(response.msg)
			}
			bindOfficeTree();
			binOfficeTreeList();
		})
	}

	/** 处理dialog打开 */
	function openDialog() {
		getAreaTree().then(response => {
			areaTree.value = proxy.handleTree(response.data, "id", "parent_id")
		});
	}

	/** 表单重置 */
	function reset() {
		form.value = {
			parent_id: undefined,
			area_id: undefined,
			name: undefined,
			code: undefined,
			type: undefined,
			grade: undefined,
			useable: '1',
			primary_person: undefined,
			deputy_person: undefined,
			address: undefined,
			zip_code: undefined,
			master: undefined,
			phone: undefined,
			fax: undefined,
			email: undefined,
			remark: undefined,
			sort: undefined
		};
		proxy.resetForm("officeRef");
	}

	/** 表单提交 */
	function submitForm() {
		proxy.$refs["officeRef"].validate(valid => {
			if (valid) {
				if (form.value.id) {
					updateOffice(form.value).then(response => {
						if (response.code == 200) {
							proxy.$modal.msgSuccess(response.msg)
						} else {
							proxy.$modal.msgError(response.msg)
						}
						bindOfficeTree();
						binOfficeTreeList();
					})
				} else {
					addOffice(form.value).then(response => {
						if (response.code == 200) {
							proxy.$modal.msgSuccess(response.msg)
						} else {
							proxy.$modal.msgError(response.msg)
						}
						bindOfficeTree();
						binOfficeTreeList();
					})
				}
			}
		})
	}

	/**
	 * 绑定机构树状图数据
	 */
	function bindOfficeTree() {
		getOfficeTree().then(response => {
			officeTree.value = response.data;
		});
	}

	/**
	 * 绑定机构树状列表数据
	 */
	function binOfficeTreeList() {
		loading.value = true;
		getOfficeTreeList().then(response => {
			officeTreeList.value = response.data;
			expands.value = [];
			loading.value = false;
		});
	}

	bindOfficeTree();
	binOfficeTreeList();
</script>

<style lang="scss" scoped>
.office-label {
    height: 40px;
    background: #f8fcff;
    line-height: 40px;
    padding-left: 10px;
    font-weight: bold;
    border: 0.5px solid #e2e2e2;
    border-radius: 5px;
}

.app-container {
    padding-top: 0px;
}
</style>
